/*
	NotifyX 版本: v1
	开发者:阿豪
	gitee: https://gitee.com/mishihao/notify-x/tree/master/
*/

(function(global) {
  'use strict';

// 内置SVG图标配置
  const icons = {
    info: `<svg viewBox="0 0 24 24" width="20" height="20" fill="#3498db">
      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
    </svg>`,
    success: `<svg viewBox="0 0 24 24" width="20" height="20" fill="#2ecc71">
      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
    </svg>`,
    warning: `<svg viewBox="0 0 24 24" width="20" height="20" fill="#e6a23c">
      <path d="M12 2L1 21h22L12 2zm0 4l7.53 13H4.47L12 6zm-1 4v4h2v-4h-2zm0 6v2h2v-2h-2z"/>
    </svg>`,
    error: `<svg viewBox="0 0 24 24" width="20" height="20" fill="#e74c3c">
      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
    </svg>`,
    confirm: `<svg viewBox="0 0 24 24" width="20" height="20" fill="#3498db">
      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/>
    </svg>`,
    close: `<svg viewBox="0 0 24 24" width="16" height="16" fill="#999">
      <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
    </svg>`
	
	
  };

  // 颜色配置（保持不变）
  const colors = {
    info: '#3498db',
    success: '#2ecc71',
    warning: '#e6a23c',
    error: '#e74c3c',
    confirm: '#3498db'
  };

// 注册自定义元素
class NotifyXModal extends HTMLElement {
  constructor() {
    super();
    // 自动隐藏原始内容（保持与之前相同的隐藏逻辑）
    this.style.display = 'none';
  }
  
  // 可选的公开方法
  showContent() {
    this.style.display = 'block';
  }
  
  hideContent() {
    this.style.display = 'none';
  }
}

// 注册自定义标签
customElements.define('notifyx-modal', NotifyXModal);

  // HTML转义函数（优化：使用更高效的正则表达式）
  function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe.toString().replace(/[&<>"']/g, 
      match => ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      }[match])
    );
  }

  /* ========== 动画优化工具函数 ========== */
  const Animator = {
    // 使用requestAnimationFrame优化动画
    animate: (element, styles, duration = 300) => {
      return new Promise(resolve => {
        const startTime = performance.now();
        const originalStyles = {};
        
        // 保存原始样式
        Object.keys(styles).forEach(prop => {
          originalStyles[prop] = element.style[prop];
        });
        
        const animateFrame = (currentTime) => {
          const elapsed = currentTime - startTime;
          const progress = Math.min(elapsed / duration, 1);
          
          // 应用过渡样式
          Object.keys(styles).forEach(prop => {
            element.style[prop] = styles[prop];
          });
          
          if (progress < 1) {
            requestAnimationFrame(animateFrame);
          } else {
            resolve();
          }
        };
        
        requestAnimationFrame(animateFrame);
      });
    },
    
    // 硬件加速优化
    enableHardwareAcceleration: (element) => {
      element.style.willChange = 'transform, opacity';
      element.style.backfaceVisibility = 'hidden';
      element.style.perspective = '1000px';
    },
    
    // 清理硬件加速
    disableHardwareAcceleration: (element) => {
      element.style.willChange = '';
      element.style.backfaceVisibility = '';
      element.style.perspective = '';
    }
  };

  /* ========== 模态弹窗 ========== */
  function msgbox(message, title = "提示", type = "info", html = false) {
    const modal = document.createElement('div');
    modal.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 9999;
      opacity: 0;
      transition: opacity 0.3s;
    `;

    const modalContent = document.createElement('div');
    modalContent.style.cssText = `
      background-color: #fff;
      border-radius: 8px;
      width: 350px;
      max-width: 90%;
      box-shadow: 0 2px 12px rgba(0,0,0,0.1);
      transform: translateY(-20px);
      transition: all 0.3s;
      overflow: hidden;
    `;

    // 应用硬件加速
    Animator.enableHardwareAcceleration(modalContent);

    modalContent.innerHTML = `
      <div style="
        padding: 15px 20px;
        border-bottom: 1px solid #ebeef5;
        display: flex;
        align-items: center;
      ">
        <div style="
          color: ${colors[type]};
          font-size: 20px;
          margin-right: 12px;
          width: 24px;
          text-align: center;
        ">${icons[type] || icons.info}</div>
        <h3 style="
          margin: 0;
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        ">${escapeHtml(title)}</h3>
      </div>
      <div style="padding: 20px;">
        <div style="
          color: #606266;
          line-height: 1.5;
          font-size: 14px;
          ${html ? '' : 'white-space: pre-wrap;'}
        ">${html ? message : escapeHtml(message)}</div>
      </div>
      <div style="
        padding: 12px 20px;
        border-top: 1px solid #ebeef5;
        text-align: right;
      ">
        <button class="notifyx-confirm-btn" style="
          padding: 8px 15px;
          background-color: #3498db;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          font-size: 14px;
        ">确定</button>
      </div>
    `;

    modal.appendChild(modalContent);
    document.body.appendChild(modal);

    // 使用优化后的动画
    Promise.all([
      Animator.animate(modal, { opacity: '1' }),
      Animator.animate(modalContent, { transform: 'translateY(0)' })
    ]);

    const close = () => {
      Promise.all([
        Animator.animate(modal, { opacity: '0' }),
        Animator.animate(modalContent, { transform: 'translateY(-20px)' })
      ]).then(() => {
        modal.remove();
        Animator.disableHardwareAcceleration(modalContent);
      });
    };

    modalContent.querySelector('.notifyx-confirm-btn').onclick = close;
    modal.onclick = (e) => e.target === modal && close();
  }

/* ========== 顶部消息 ========== */
function message(msg, type = "info", html = false) {
    // 消息队列管理
    const MESSAGE_QUEUE = window.__notifyx_message_queue || (window.__notifyx_message_queue = {
        elements: [],
        positions: {},
        updatePositions() {
            let verticalOffset = 20; // 初始位置
            this.elements.forEach(el => {
                el.style.top = `${verticalOffset}px`;
                verticalOffset += el.offsetHeight + 10; // 10px 间距
            });
        }
    });

    const msgEl = document.createElement('div');
    msgEl.style.cssText = `
        position: fixed;
        top: -100px;
        left: 50%;
        transform: translateX(-50%);
        padding: 15px 20px;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        border-left: 4px solid ${colors[type]};
        display: flex;
        align-items: center;
        z-index: 9999;
        transition: top 0.4s cubic-bezier(0.68, -0.55, 0.27, 1.55);
    `;

    msgEl.innerHTML = `
        <div style="
            color: ${colors[type]};
            font-size: 18px;
            margin-right: 12px;
            width: 20px;
            text-align: center;
        ">${icons[type] || icons.info}</div>
        <div style="
            font-size: 14px;
            color: #606266;
            ${html ? '' : 'white-space: pre-wrap;'}
        ">${html ? msg : escapeHtml(msg)}</div>
    `;

    document.body.appendChild(msgEl);
    MESSAGE_QUEUE.elements.push(msgEl);

    // 使用requestAnimationFrame优化入场动画
    requestAnimationFrame(() => {
        MESSAGE_QUEUE.updatePositions();
    });

    // 使用setTimeout优化定时器管理
    let timeoutId;
    const closeNotification = () => {
        msgEl.style.top = '-100px';
        timeoutId = setTimeout(() => {
            msgEl.remove();
            const index = MESSAGE_QUEUE.elements.indexOf(msgEl);
            if (index > -1) {
                MESSAGE_QUEUE.elements.splice(index, 1);
                MESSAGE_QUEUE.updatePositions();
            }
        }, 400);
    };

    // 自动关闭
    timeoutId = setTimeout(closeNotification, 3000);
    
    // 清理定时器
    msgEl.cleanup = () => {
        clearTimeout(timeoutId);
        closeNotification();
    };
}


/* ========== 确认对话框 ========== */
function confirm(message, title, callback, html = false) {
// 参数处理：判断是否是回调风格调用
    const isCallbackStyle = typeof callback === 'function';
    
    // 处理 Promise 风格调用 (title 可能是 boolean 或 function)
    if (typeof title === 'function' || typeof title === 'boolean') {
        html = typeof title === 'boolean' ? title : html;
        callback = typeof title === 'function' ? title : callback;
        title = "确认操作"; // 提供默认标题
    }
    
    return new Promise((resolve) => {
        const modal = document.createElement('div');
        modal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            opacity: 0;
            transition: opacity 0.3s;
        `;

        const modalContent = document.createElement('div');
        modalContent.style.cssText = `
            background-color: #fff;
            border-radius: 8px;
            width: 350px;
            max-width: 90%;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
            transform: translateY(-20px);
            transition: all 0.3s;
            overflow: hidden;
        `;

        modalContent.innerHTML = `
            <div style="
                padding: 15px 20px;
                border-bottom: 1px solid #ebeef5;
                display: flex;
                align-items: center;
            ">
                <div style="
                    color: ${colors.confirm};
                    font-size: 20px;
                    margin-right: 12px;
                    width: 24px;
                    text-align: center;
                ">${icons.confirm}</div>
                <h3 style="
                    margin: 0;
                    font-size: 16px;
                    font-weight: 500;
                    color: #303133;
                ">${escapeHtml(title)}</h3>
            </div>
            <div style="padding: 20px;">
                <div style="
                    color: #606266;
                    line-height: 1.5;
                    font-size: 14px;
                    ${html ? '' : 'white-space: pre-wrap;'}
                ">${html ? message : escapeHtml(message)}</div>
            </div>
            <div style="
                padding: 12px 20px;
                border-top: 1px solid #ebeef5;
                display: flex;
                justify-content: flex-end;
                gap: 10px;
            ">
                <button class="notifyx-cancel-btn" style="
                    padding: 8px 15px;
                    background-color: #f1f1f1;
                    color: #333;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    cursor: pointer;
                    font-size: 14px;
                ">取消</button>
                <button class="notifyx-confirm-btn" style="
                    padding: 8px 15px;
                    background-color: #3498db;
                    color: white;
                    border: none;
                    border-radius: 4px;
                    cursor: pointer;
                    font-size: 14px;
                ">确定</button>
            </div>
        `;

        modal.appendChild(modalContent);
        document.body.appendChild(modal);

        // 显示动画
        setTimeout(() => {
            modal.style.opacity = '1';
            modalContent.style.transform = 'translateY(0)';
        }, 10);

        const close = () => {
            modal.style.opacity = '0';
            setTimeout(() => modal.remove(), 300);
        };

        // 点击取消按钮
        modalContent.querySelector('.notifyx-cancel-btn').onclick = () => {
            if (isCallbackStyle) callback(false);
            resolve(false);
            close();
        };

        // 点击确认按钮
        modalContent.querySelector('.notifyx-confirm-btn').onclick = () => {
            if (isCallbackStyle) callback(true);
            resolve(true);
            close();
        };

        // 点击遮罩层
        modal.onclick = (e) => {
            if (e.target === modal) {
                if (isCallbackStyle) callback(false);
                resolve(false);
                close();
            }
        };
    });
}

/* ========== 通知组件 ========== */
function notification(options) {
    const {
        title = '通知',
        message = '',
        type = 'info',
        position = 'top-right',
        duration = 3000,
        close = true,
        html = false
    } = options;

    // 通知队列管理
    const NOTIFICATION_QUEUE = window.__notifyx_notification_queue || (window.__notifyx_notification_queue = {
        elements: [],
        positions: {},
        updatePositions(pos) {
            const verticalGap = 10; // 通知之间的垂直间距
            let verticalOffset = 20; // 初始位置
            
            // 过滤当前位置的通知并按创建时间排序
            const positionNotifications = this.elements
                .filter(el => el.dataset.position === pos)
                .sort((a, b) => a.dataset.timestamp - b.dataset.timestamp);
            
            positionNotifications.forEach(el => {
                el.style[pos.includes('top') ? 'top' : 'bottom'] = `${verticalOffset}px`;
                verticalOffset += el.offsetHeight + verticalGap;
            });
        }
    });

    const notifyEl = document.createElement('div');
    notifyEl.style.cssText = `
        position: fixed;
        width: 330px;
        padding: 14px 20px;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        transition: all 0.3s cubic-bezier(0.68, -0.55, 0.27, 1.55);
        z-index: 9999;
        display: flex;
        opacity: 0;
    `;

    // 设置位置和动画方向
    const positionStyles = {
        'top-right': { 
            top: '20px', 
            right: '-400px',
            transform: 'translateX(0)'
        },
        'top-left': { 
            top: '20px', 
            left: '-400px',
            transform: 'translateX(0)'
        },
        'bottom-right': { 
            bottom: '20px', 
            right: '-400px',
            transform: 'translateX(0)'
        },
        'bottom-left': { 
            bottom: '20px', 
            left: '-400px',
            transform: 'translateX(0)'
        }
    };
    
    Object.assign(notifyEl.style, positionStyles[position] || positionStyles['top-right']);
    notifyEl.dataset.position = position;
    notifyEl.dataset.timestamp = Date.now();

    notifyEl.innerHTML = `
        <div style="
            color: ${colors[type]};
            font-size: 20px;
            margin-right: 12px;
            width: 24px;
            text-align: center;
        ">${icons[type] || icons.info}</div>
        <div style="flex: 1;">
            <div style="
                font-size: 16px;
                color: #303133;
                margin-bottom: 6px;
                font-weight: 500;
            ">${escapeHtml(title)}</div>
            <div style="
                font-size: 14px;
                color: #606266;
                line-height: 1.5;
                ${html ? '' : 'white-space: pre-wrap;'}
            ">${html ? message : escapeHtml(message)}</div>
        </div>
        ${close ? `
        <button class="notifyx-close" style="
            background: none;
            border: none;
            color: #999;
            cursor: pointer;
            font-size: 16px;
            align-self: flex-start;
            padding: 0 0 0 10px;
        "><i class="fa-solid fa-xmark"></i></button>
        ` : ''}
    `;

    document.body.appendChild(notifyEl);
    NOTIFICATION_QUEUE.elements.push(notifyEl);

    // 应用硬件加速
    Animator.enableHardwareAcceleration(notifyEl);

    // 显示动画
    requestAnimationFrame(() => {
        notifyEl.style.opacity = '1';
        notifyEl.style[position.includes('left') ? 'left' : 'right'] = '20px';
        NOTIFICATION_QUEUE.updatePositions(position);
    });

    // 关闭功能
    const closeNotification = () => {
        notifyEl.style.opacity = '0';
        notifyEl.style[position.includes('left') ? 'left' : 'right'] = '-400px';
        
        setTimeout(() => {
            const index = NOTIFICATION_QUEUE.elements.indexOf(notifyEl);
            if (index > -1) {
                NOTIFICATION_QUEUE.elements.splice(index, 1);
                NOTIFICATION_QUEUE.updatePositions(position);
            }
            notifyEl.remove();
            Animator.disableHardwareAcceleration(notifyEl);
        }, 300);
    };

    // 点击关闭按钮
    if (close) {
        notifyEl.querySelector('.notifyx-close').onclick = closeNotification;
    }
    
    // 自动关闭（优化定时器管理）
    let timeoutId;
    if (duration > 0) {
        timeoutId = setTimeout(closeNotification, duration);
    }
    
    // 清理函数
    notifyEl.cleanup = () => {
        if (timeoutId) clearTimeout(timeoutId);
        closeNotification();
    };
}
  
  /* ========== iframe模态框 ========== */
  function iframeModal(options) {
    const {
      url,
      title = "网页预览",
      width = 980,
      height = 650,
      resizable = false,
      draggable = false
    } = options;

    // 创建模态框容器
    const modal = document.createElement('div');
    modal.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 9999;
      opacity: 0;
      transition: opacity 0.3s;
    `;

    // 模态框内容
    const modalContent = document.createElement('div');
    modalContent.style.cssText = `
      background-color: #fff;
      border-radius: 5px;
      width: ${width}px;
      height: ${height}px;
      min-width: 300px;
      min-height: 200px;
      max-width: 90%;
      max-height: 90%;
      box-shadow: 0 2px 12px rgba(0,0,0,0.1);
      display: flex;
      flex-direction: column;
      position: absolute;
      overflow: hidden;
      will-change: transform, width, height;
    `;

    modalContent.innerHTML = `
      <div class="modal-header" style="
        padding: 15px 20px;
        border-bottom: 1px solid #ebeef5;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-shrink: 0;
        cursor: ${draggable ? 'move' : 'default'};
        user-select: none;
      ">
        <h3 style="
          margin: 0;
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        ">${title}</h3>
        <button class="notifyx-close" style="
          background: none;
          border: none;
          color: #999;
          cursor: pointer;
          font-size: 20px;
          line-height: 1;
        ">×</button>
      </div>
      <iframe 
        src="${url}" 
        style="
          flex: 1;
          width: 100%;
          height: 100%;
          border: none;
        "
        allowfullscreen
      ></iframe>
    `;

    // 添加可拖拽调整大小的边缘
    if (resizable) {
      const resizeHandles = [
        { class: 'resize-right', style: 'right:0; top:0; width:8px; height:100%; cursor:e-resize;' },
        { class: 'resize-bottom', style: 'bottom:0; left:0; width:100%; height:8px; cursor:s-resize;' },
        { class: 'resize-corner', style: 'right:0; bottom:0; width:16px; height:16px; cursor:se-resize;' }
      ];
      
      resizeHandles.forEach(handle => {
        const handleEl = document.createElement('div');
        handleEl.className = `resize-handle ${handle.class}`;
        handleEl.style.cssText = `position:absolute; ${handle.style}`;
        modalContent.appendChild(handleEl);
      });
    }

    modal.appendChild(modalContent);
    document.body.appendChild(modal);

    // 应用硬件加速
    Animator.enableHardwareAcceleration(modalContent);

    // 立即显示（使用优化动画）
    Animator.animate(modal, { opacity: '1' });

    // 关闭功能（仅通过按钮）
    const close = () => {
      Animator.animate(modal, { opacity: '0' }).then(() => {
        document.removeEventListener('keydown', handleKeyDown);
        modal.remove();
        Animator.disableHardwareAcceleration(modalContent);
      });
    };
    modalContent.querySelector('.notifyx-close').onclick = close;

    // 拖拽移动功能
    if (draggable) {
      const header = modalContent.querySelector('.modal-header');
      let isDragging = false;
      let startX, startY, startLeft, startTop;
      let dragFrameId = null;

      header.addEventListener('mousedown', (e) => {
        if (e.target.closest('.notifyx-close')) return;
        
        e.preventDefault();
        isDragging = true;
        
        const rect = modalContent.getBoundingClientRect();
        startX = e.clientX;
        startY = e.clientY;
        startLeft = rect.left;
        startTop = rect.top;
        
        document.body.style.userSelect = 'none';
        modalContent.style.transition = 'none';
        modalContent.style.cursor = 'move';
        
        document.addEventListener('mousemove', dragMove);
        document.addEventListener('mouseup', stopDrag);
      });

      const dragMove = (e) => {
        if (!isDragging) return;
        
        if (dragFrameId) {
          cancelAnimationFrame(dragFrameId);
        }
        
        dragFrameId = requestAnimationFrame(() => {
          const dx = e.clientX - startX;
          const dy = e.clientY - startY;
          
          const newLeft = Math.max(0, Math.min(startLeft + dx, window.innerWidth - modalContent.offsetWidth));
          const newTop = Math.max(0, Math.min(startTop + dy, window.innerHeight - modalContent.offsetHeight));
          
          modalContent.style.left = `${newLeft}px`;
          modalContent.style.top = `${newTop}px`;
        });
      };

      const stopDrag = () => {
        if (!isDragging) return;
        
        isDragging = false;
        
        if (dragFrameId) {
          cancelAnimationFrame(dragFrameId);
          dragFrameId = null;
        }
        
        document.body.style.userSelect = '';
        modalContent.style.transition = 'all 0.3s';
        modalContent.style.cursor = '';
        
        document.removeEventListener('mousemove', dragMove);
        document.removeEventListener('mouseup', stopDrag);
      };
    }

    // 拖拽调整大小功能
    if (resizable) {
      let isResizing = false;
      let currentHandle = null;
      let startX, startY, startWidth, startHeight;
      let resizeFrameId = null;

      const startResize = (e, handleType) => {
        e.preventDefault();
        e.stopPropagation();
        
        isResizing = true;
        currentHandle = handleType;
        startX = e.clientX;
        startY = e.clientY;
        startWidth = parseInt(document.defaultView.getComputedStyle(modalContent).width, 10);
        startHeight = parseInt(document.defaultView.getComputedStyle(modalContent).height, 10);
        
        modalContent.style.transition = 'none';
        document.body.style.userSelect = 'none';
        
        document.addEventListener('mousemove', resize);
        document.addEventListener('mouseup', stopResize);
      };

      const resize = (e) => {
        if (!isResizing) return;
        
        if (resizeFrameId) {
          cancelAnimationFrame(resizeFrameId);
        }
        
        resizeFrameId = requestAnimationFrame(() => {
          const dx = e.clientX - startX;
          const dy = e.clientY - startY;
          
          if (currentHandle === 'resize-right' || currentHandle === 'resize-corner') {
            const newWidth = Math.max(300, Math.min(startWidth + dx, window.innerWidth * 0.9));
            modalContent.style.width = `${newWidth}px`;
          }
          
          if (currentHandle === 'resize-bottom' || currentHandle === 'resize-corner') {
            const newHeight = Math.max(200, Math.min(startHeight + dy, window.innerHeight * 0.9));
            modalContent.style.height = `${newHeight}px`;
          }
        });
      };

      const stopResize = () => {
        if (!isResizing) return;
        
        isResizing = false;
        
        if (resizeFrameId) {
          cancelAnimationFrame(resizeFrameId);
          resizeFrameId = null;
        }
        
        modalContent.style.transition = 'all 0.3s';
        document.body.style.userSelect = '';
        
        document.removeEventListener('mousemove', resize);
        document.removeEventListener('mouseup', stopResize);
      };

      // 绑定拖拽手柄
      const handles = modalContent.querySelectorAll('.resize-handle');
      handles.forEach(handle => {
        const handleType = handle.classList[1];
        handle.addEventListener('mousedown', (e) => startResize(e, handleType));
      });
    }

    // ESC键关闭功能
    const handleKeyDown = (e) => {
      if (e.key === 'Escape') {
        close();
      }
    };
    document.addEventListener('keydown', handleKeyDown);

    // 清理函数
    modal.cleanup = () => {
      document.removeEventListener('keydown', handleKeyDown);
      close();
    };

    return modal;
  }
  
  const NxDataBinding = {
  // 存储所有模态框的数据
  stores: new Map(),

  // 初始化绑定
  init(modalId, formElement) {
    const store = {};
    this.stores.set(modalId, store);

    // 查找所有带 nx-value 的元素
    formElement.querySelectorAll('[nx-value]').forEach(el => {
      const key = el.getAttribute('nx-value');
      
      // 初始化存储值
      store[key] = el.value || '';
      
      // 双向绑定
      el.addEventListener('input', () => {
        store[key] = el.value;
      });
    });
  },

  // 获取表单数据
  getData(modalId) {
    return this.stores.get(modalId) || {};
  }
};

// 页面加载时自动隐藏所有 notify-modal 元素
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('[notify-modal]').forEach(el => {
        el.setAttribute('data-notifyx-original-display', el.style.display);
        el.style.display = 'none';
    });
});

function modal(options) {
    const {
        title = "提示",
        width = 500,
        height = "auto",
        hidden = false,
        submitText = "确定",
        cancelText = "取消",
        onSubmit = null,
        onCancel = null,
        modalId = null
    } = options;

    // 查找现有的模态框元素
    let modalElement = modalId ? document.querySelector(`[notify-modal="${modalId}"]`) : null;
    
    // 如果没有找到指定ID的模态框，查找第一个notify-modal元素
    if (!modalElement) {
        modalElement = document.querySelector('[notify-modal]');
    }
    
    // 如果仍然没有找到，创建一个空的模态框
    if (!modalElement) {
        modalElement = document.createElement('div');
        modalElement.setAttribute('notify-modal', 'default');
        document.body.appendChild(modalElement);
    }

    // 自动隐藏原始内容（新增的核心代码）
    const originalDisplay = modalElement.style.display;
    modalElement.style.display = 'none';

    // 创建模态框容器
    const modalContainer = document.createElement('div');
    modalContainer.className = 'notifyx-modal-container';
    modalContainer.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
        display: ${hidden ? 'none' : 'flex'};
        justify-content: center;
        align-items: center;
        z-index: 9999;
        opacity: 0;
        transition: opacity 0.3s;
    `;

    // 模态框内容
    const modalContent = document.createElement('div');
    modalContent.className = 'notifyx-modal-content';
    modalContent.style.cssText = `
        background-color: #fff;
        border-radius: 8px;
        width: ${typeof width === 'number' ? `${width}px` : width};
        ${height !== 'auto' ? `height: ${typeof height === 'number' ? `${height}px` : height};` : ''}
        min-width: 300px;
        max-width: 90%;
        max-height: 90%;
        box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        display: flex;
        flex-direction: column;
        overflow: hidden;
        transform: translateY(-20px);
        transition: all 0.3s;
    `;

    // 克隆原始内容以避免影响原始DOM
    const contentClone = modalElement.cloneNode(true);
    contentClone.style.display = 'block';
    contentClone.style.padding = '0';
    contentClone.style.margin = '0';
    contentClone.removeAttribute('notify-modal');

    // 构建模态框结构
    modalContent.innerHTML = `
        <div class="notifyx-modal-header" style="
            padding: 15px 20px;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        ">
            <h3 style="
                margin: 0;
                font-size: 16px;
                font-weight: 500;
                color: #303133;
            ">${title}</h3>
            <button class="notifyx-modal-close" style="
                background: none;
                border: none;
                color: #999;
                cursor: pointer;
                font-size: 20px;
                line-height: 1;
            ">×</button>
        </div>
        <div class="notifyx-modal-body" style="
            padding: 20px;
            flex: 1;
            overflow-y: auto;
        "></div>
        <div class="notifyx-modal-footer" style="
            padding: 12px 20px;
            border-top: 1px solid #ebeef5;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        ">
            <button class="notifyx-modal-cancel" style="
                padding: 8px 15px;
                background-color: #f1f1f1;
                color: #333;
                border: 1px solid #ddd;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
            ">${cancelText}</button>
            <button class="notifyx-modal-submit" style="
                padding: 8px 15px;
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
            ">${submitText}</button>
        </div>
    `;


    // 自动隐藏所有带有 notify-modal 属性的元素
    document.querySelectorAll('[notify-modal]').forEach(el => {
        if (!el.hasAttribute('data-notifyx-original-display')) {
            el.setAttribute('data-notifyx-original-display', el.style.display);
            el.style.display = 'none';
        }
    });

    // 将克隆的内容插入到模态框体中
    const modalBody = modalContent.querySelector('.notifyx-modal-body');
    modalBody.appendChild(contentClone);

    modalContainer.appendChild(modalContent);
    document.body.appendChild(modalContainer);

    // 应用硬件加速
    Animator.enableHardwareAcceleration(modalContent);

    // 显示/隐藏方法
    const show = () => {
        modalContainer.style.display = 'flex';
        NxDataBinding.init(options.modalId || 'default', modalBody);
        Promise.all([
            Animator.animate(modalContainer, { opacity: '1' }),
            Animator.animate(modalContent, { transform: 'translateY(0)' })
        ]);
    };

    const hide = () => {
        Promise.all([
            Animator.animate(modalContainer, { opacity: '0' }),
            Animator.animate(modalContent, { transform: 'translateY(-20px)' })
        ]).then(() => {
            modalContainer.style.display = 'none';
        });
    };

    // 如果初始不隐藏，则显示
    if (!hidden) {
        show();
    }

    // 事件处理
    const closeBtn = modalContent.querySelector('.notifyx-modal-close');
    const cancelBtn = modalContent.querySelector('.notifyx-modal-cancel');
    const submitBtn = modalContent.querySelector('.notifyx-modal-submit');

    const handleClose = () => {
        hide();
        if (typeof onCancel === 'function') {
            onCancel();
        }
    };

    const handleSubmit = () => {
        if (typeof onSubmit === 'function') {
            onSubmit();
        }
        hide();
    };

    closeBtn.onclick = handleClose;
    cancelBtn.onclick = handleClose;
    submitBtn.onclick = handleSubmit;
    modalContainer.onclick = (e) => {
        if (e.target === modalContainer) {
            handleClose();
        }
    };

    // 返回控制对象
    return {
        show,
        hide,
        element: modalContent,
        container: modalContainer,
        getFormData: () => NxDataBinding.getData(options.modalId || 'default'),
        destroy: () => {
            // 恢复原始元素的显示状态
            modalElement.style.display = originalDisplay;
            modalContainer.remove();
            Animator.disableHardwareAcceleration(modalContent);
        }
    };
}

const NxFormBinding = {
  // 存储所有表单数据
  forms: new Map(),
  
  // 初始化表单绑定
  init(selector) {
    // 支持传入元素或选择器
    const formElement = typeof selector === 'string' 
      ? document.querySelector(selector)
      : selector;
    
    if (!formElement) {
      console.error('Form element not found');
      return null;
    }
    
    const formData = {};
    const formId = formElement.id || `form_${Date.now()}`;
    
    // 查找所有带 nx-value 的元素
    formElement.querySelectorAll('[nx-value]').forEach(el => {
      const key = el.getAttribute('nx-value');
      
      // 初始化存储值
      formData[key] = el.value || '';
      
      // 双向绑定
      el.addEventListener('input', () => {
        formData[key] = el.value;
      });
    });
    
    this.forms.set(formId, formData);
    return formId;
  },
  
  // 获取表单数据
  getData(formId) {
    return this.forms.get(formId) || {};
  },
  
  // 获取所有表单数据
  getAll() {
    return Object.fromEntries(this.forms);
  }
};

  // 暴露API
  global.$notify = {
    msgbox: msgbox,
    confirm: confirm,
    notification: notification,
    iframe: iframeModal,
	modal: modal,
    
// 表单绑定功能
  form: {
    // 初始化表单绑定（支持元素或选择器）
    bind: (selector) => NxFormBinding.init(selector),
    
    // 获取特定表单数据
    get: (formId) => NxFormBinding.getData(formId),
    
    // 获取所有表单数据
    all: () => NxFormBinding.getAll()
  },
	
    info: (msg, title, html) => msgbox(msg, title, 'info', html),
    success: (msg, title, html) => msgbox(msg, title, 'success', html),
    warning: (msg, title, html) => msgbox(msg, title, 'warning', html),
    error: (msg, title, html) => msgbox(msg, title, 'error', html),
    
    msg: {
      info: (msg, html) => message(msg, 'info', html),
      success: (msg, html) => message(msg, 'success', html),
      warning: (msg, html) => message(msg, 'warning', html),
      error: (msg, html) => message(msg, 'error', html)
    }
  };

})(window);